<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>值班表生成器</title>
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <link href="/css/style.css" rel="stylesheet">
    <link href="/css/bootstrap-icons.css" rel="stylesheet">
    <link href="/css/sweetalert2.min.css" rel="stylesheet">
    <link href="/css/select2.min.css" rel="stylesheet" />
    <style>
        .preview-container {
            position: relative;
            width: 100%;
            max-width: 540px;
            margin: 0 auto;
            background: #f8f9fa;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
        }

        #canvas {
            width: 100%;
            height: auto;
        }

        .table-input {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.05);
        }

        .duty-row {
            background: white;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 10px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
            transition: all 0.3s ease;
        }

        .duty-row:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }

        .color-picker {
            width: 50px;
            height: 38px;
            padding: 0;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        .color-picker::-webkit-color-swatch-wrapper {
            padding: 0;
        }

        .color-picker::-webkit-color-swatch {
            border: none;
            border-radius: 5px;
        }

        .settings-panel {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.05);
        }

        .nav-pills .nav-link.active {
            background-color: #4b6cb7;
        }

        .nav-pills .nav-link {
            color: #4b6cb7;
        }

        .navbar {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .navbar-brand {
            font-weight: 600;
            color: #4f46e5;
        }

        .nav-link {
            color: #4b5563;
            transition: all 0.3s ease;
            padding: 0.5rem 1rem;
            border-radius: 0.5rem;
        }

        .nav-link:hover {
            color: #4f46e5;
            background: rgba(79, 70, 229, 0.1);
        }

        .nav-link.active {
            color: #4f46e5;
            background: rgba(79, 70, 229, 0.1);
        }

        .navbar-toggler {
            border: none;
            padding: 0.5rem;
        }

        .navbar-toggler:focus {
            box-shadow: none;
            outline: none;
        }

        .dropdown-menu {
            border: none;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            border-radius: 0.5rem;
        }

        .dropdown-item {
            padding: 0.5rem 1rem;
            color: #4b5563;
            transition: all 0.3s ease;
        }

        .dropdown-item:hover {
            color: #4f46e5;
            background: rgba(79, 70, 229, 0.1);
        }

        @media (max-width: 768px) {
            .navbar-nav {
                padding: 1rem 0;
            }

            .nav-link {
                padding: 0.5rem 1rem;
            }
        }

        .footer-settings {
            margin-top: 20px;
        }

        .signature-settings {
            margin-top: 20px;
        }

        .batch-actions {
            margin-top: 10px;
            margin-bottom: 20px;
        }
        .swal2-container {
            z-index: 10000 !important;
        }

        .modal-backdrop {
            z-index: 9999 !important;
        }

        .modal {
            z-index: 10000 !important;
        }

        .select2-container {
            width: 100% !important;
        }

        .select2-selection {
            height: 38px !important;
            padding: 5px !important;
            border: 1px solid #ced4da !important;
            border-radius: 0.375rem !important;
        }

        .select2-selection__arrow {
            height: 36px !important;
        }

        .select2-container--default .select2-selection--single {
            background-color: #fff;
            border: 1px solid #ced4da;
            border-radius: 0.375rem;
        }

        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 28px;
            color: #212529;
        }

        .select2-container--default .select2-selection--single .select2-selection__placeholder {
            color: #6c757d;
        }

        .select2-container--default .select2-results__option--highlighted[aria-selected] {
            background-color: #4f46e5;
        }
    </style>
</head>
<body>
<!-- 导航栏 -->
<nav class="navbar navbar-expand-lg sticky-top">
    <div class="container">
        <a class="navbar-brand" href="/index">
            <i class="bi bi-clipboard-data me-2"></i>运维年报系统
        </a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
            <i class="bi bi-list"></i>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav me-auto">
                <li class="nav-item">
                    <a class="nav-link" href="/index">
                        <i class="bi bi-house me-1"></i>首页
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/hospitals/hospital-import">
                        <i class="bi bi-hospital me-1"></i>医院管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/report-list">
                        <i class="bi bi-file-text me-1"></i>报告列表
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link active" href="/reports/generateZhiBan">
                        <i class="bi bi-file-text me-1"></i>值班表生成
                    </a>
                </li>
            </ul>
            <ul class="navbar-nav">
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                        <i class="bi bi-person-circle me-1"></i>
                        <span th:text="${userName}">用户名</span>
                    </a>
                    <ul class="dropdown-menu dropdown-menu-end">
                        <li>
                            <a class="dropdown-item" href="#" onclick="openChangePasswordModal()">
                                <i class="bi bi-key me-2"></i>修改密码
                            </a>
                        </li>
                        <li>
                            <hr class="dropdown-divider">
                        </li>
                        <li>
                            <a class="dropdown-item text-danger" href="/logout">
                                <i class="bi bi-box-arrow-right me-2"></i>退出登录
                            </a>
                        </li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</nav>

<!-- 修改密码模态框 -->
<div class="modal fade" id="changePasswordModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">修改密码</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">原密码</label>
                    <input type="password" class="form-control" id="oldPassword">
                </div>
                <div class="mb-3">
                    <label class="form-label">新密码</label>
                    <input type="password" class="form-control" id="newPassword">
                </div>
                <div class="mb-3">
                    <label class="form-label">确认新密码</label>
                    <input type="password" class="form-control" id="confirmPassword">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="changePassword()">确认修改</button>
            </div>
        </div>
    </div>
</div>
<div class="container-fluid py-4">
    <div class="row">
        <!-- 左侧设置面板 -->
        <div class="col-md-6 mb-4">
            <div class="settings-panel">
                <h4 class="mb-4"><i class="bi bi-gear-fill me-2"></i>值班表设置</h4>

                <!-- 导航标签 -->
                <ul class="nav nav-pills mb-4" role="tablist">
                    <li class="nav-item">
                        <a class="nav-link active" data-bs-toggle="pill" href="#content">内容设置</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" data-bs-toggle="pill" href="#style">样式设置</a>
                    </li>
                </ul>

                <!-- 标签内容 -->
                <div class="tab-content">
                    <!-- 内容设置 -->
                    <div id="content" class="tab-pane fade show active">
                        <!--                            <div class="mb-4">-->
                        <!--                                <label class="form-label">标题</label>-->
                        <!--                                <input type="text" class="form-control" id="titleInput" value="值班安排表">-->
                        <!--                            </div>-->

                        <div class="mb-4">
                            <label class="form-label">值班人员安排</label>
                            <div id="dutyList">
                                <!-- 值班行将通过JS动态添加 -->
                            </div>
                            <div class="batch-actions">
                                <button class="btn btn-sm btn-outline-primary" onclick="copyLastRow()">
                                    <i class="bi bi-files"></i> 复制上一行
                                </button>
                                <button class="btn btn-sm btn-outline-success" onclick="showBatchAddModal()">
                                    <i class="bi bi-plus-circle"></i> 批量添加
                                </button>
                            </div>
                        </div>

                        <div class="mb-4">
                            <label class="form-label">底部说明文字</label>
                            <textarea class="form-control" id="footerText" rows="2">感谢各位同仁的辛勤付出，让我们携手共创美好未来！感谢各位同仁的辛勤付出，让我们携手共创美好未来！感谢各位同仁的辛勤付出，让我们携手共创美好未来！感谢各位同仁的辛勤付出，让我们携手共创美好未来！</textarea>
                        </div>
                        <div class="mb-4">
                            <label class="form-label">底部感谢内容</label>
                            <textarea class="form-control" id="footerThankText"
                                      rows="2">感谢您一直以来的信任和支持,祝您节日愉快!</textarea>
                        </div>

                        <div class="mb-4">
                            <label class="form-label">签名</label>
                            <input type="text" class="form-control mb-2" id="signatureText"
                                   value="智医科技股份有限公司">
                            <input type="date" class="form-control" id="signatureDate">
                        </div>
                    </div>

                    <!-- 样式设置 -->
                    <div id="style" class="tab-pane fade">
                        <div class="row g-3">
                            <div class="col-12 mb-4">
                                <h6>背景图选择</h6>
                                <div class="row">
                                    <div class="col-md-3 mb-3">
                                        <div class="card h-100">
                                            <img src="/images/zhiban/zhibanbiao.jpg" class="card-img-top" alt="默认背景">
                                            <div class="card-body">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="radio" name="bgImage" id="bgDefault" value="zhibanbiao.jpg" checked>
                                                    <label class="form-check-label" for="bgDefault">默认背景</label>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <div class="card h-100">
                                            <img src="/images/zhiban/chunjie.jpg" class="card-img-top" alt="春节背景">
                                            <div class="card-body">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="radio" name="bgImage" id="bgSpring" value="chunjie.jpg">
                                                    <label class="form-check-label" for="bgSpring">春节背景</label>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <div class="card h-100">
                                            <img src="/images/zhiban/guoqing.jpg" class="card-img-top" alt="国庆背景">
                                            <div class="card-body">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="radio" name="bgImage" id="bgNational" value="guoqing.jpg">
                                                    <label class="form-check-label" for="bgNational">国庆背景</label>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <div class="card h-100">
                                            <img src="/images/zhiban/wuyi.jpg" class="card-img-top" alt="五一背景">
                                            <div class="card-body">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="radio" name="bgImage" id="bgLabor" value="wuyi.jpg">
                                                    <label class="form-check-label" for="bgLabor">五一背景</label>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">表格边框颜色</label>
                                <input type="color" class="color-picker form-control" id="borderColor" value="#dee2e6">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">表头背景色</label>
                                <input type="color" class="color-picker form-control" id="headerBgColor"
                                       value="#f8f9fa">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">表头文字颜色</label>
                                <input type="color" class="color-picker form-control" id="headerTextColor"
                                       value="#495057">
                            </div>
                            <div class="col-12 mt-4">
                                <h6>表格布局</h6>
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <label class="form-label">表格X坐标</label>
                                        <input type="number" class="form-control" id="tableX" value="100">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">表格Y坐标</label>
                                        <input type="number" class="form-control" id="tableY" value="550">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">表格宽度</label>
                                        <input type="number" class="form-control" id="tableWidth" value="880">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">行高</label>
                                        <input type="number" class="form-control" id="rowHeight" value="60">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">说明文字Y坐标</label>
                                        <input type="number" class="form-control" id="footerY" value="520">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">感谢文字Y坐标</label>
                                        <input type="number" class="form-control" id="thankY" value="650">
                                    </div>
                                </div>
                            </div>

                            <div class="col-12 mt-4">
                                <h6>底部文字样式</h6>
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <label class="form-label">说明文字颜色</label>
                                        <input type="color" class="color-picker form-control" id="footerColor"
                                               value="#6c757d">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">说明文字大小(px)</label>
                                        <input type="number" class="form-control" id="footerFontSize" value="20">
                                    </div>
                                </div>
                            </div>

                            <div class="col-12 mt-4">
                                <h6>感谢内容样式</h6>
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <label class="form-label">感谢文字颜色</label>
                                        <input type="color" class="color-picker form-control" id="thankColor"
                                               value="#6c757d">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">感谢文字大小(px)</label>
                                        <input type="number" class="form-control" id="thankFontSize" value="20">
                                    </div>
                                </div>
                            </div>

                            <div class="col-12 mt-4">
                                <h6>表格样式</h6>
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <label class="form-label">表格文字颜色</label>
                                        <input type="color" class="color-picker form-control" id="tableTextColor"
                                               value="#495057">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">表格文字大小(px)</label>
                                        <input type="number" class="form-control" id="tableFontSize" value="20">
                                    </div>
                                </div>
                            </div>

                            <div class="col-12 mt-4">
                                <h6>签名样式</h6>
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <label class="form-label">签名文字颜色</label>
                                        <input type="color" class="color-picker form-control" id="signatureColor"
                                               value="#495057">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">签名文字大小(px)</label>
                                        <input type="number" class="form-control" id="signatureFontSize" value="24">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">日期文字颜色</label>
                                        <input type="color" class="color-picker form-control" id="signatureDateColor"
                                               value="#495057">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">日期文字大小(px)</label>
                                        <input type="number" class="form-control" id="signatureDateFontSize" value="24">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">签名的高度(px)</label>
                                        <input type="number" class="form-control" id="signatureHeight" value="1500">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">签名的宽度(px)</label>
                                        <input type="number" class="form-control" id="signatureWeight" value="900">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 操作按钮 -->
            <div class="d-grid gap-2">
                <button class="btn btn-primary" onclick="generateImage()">
                    <i class="bi bi-download me-2"></i>导出图片
                </button>
            </div>
        </div>

        <!-- 右侧预览 -->
        <div class="col-md-6" style="position: fixed;right: 0">
            <div class="preview-container">
                <canvas id="canvas"></canvas>
            </div>
        </div>
    </div>
</div>

<!-- 批量添加模态框 -->
<div class="modal fade" id="batchAddModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">批量添加值班人员</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">日期</label>
                    <input type="text" class="form-control" id="batchDate">
                </div>
                <div class="mb-3">
                    <label class="form-label">值班人员</label>
                    <input type="text" class="form-control" id="batchName">
                </div>
                <div class="mb-3">
                    <label class="form-label">联系方式</label>
                    <input type="text" class="form-control" id="batchPhone">
                </div>
                <div class="mb-3">
                    <label class="form-label">重复次数</label>
                    <input type="number" class="form-control" id="batchCount" min="1" value="1">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="batchAddRows()">确定</button>
            </div>
        </div>
    </div>
</div>

<script src="/js/bootstrap.bundle.min.js"></script>
<script>
    let dutyRows = [];

    // 初始化日期选择器
    document.getElementById('signatureDate').valueAsDate = new Date();
    // 修改密码模态框实例
    let changePasswordModal = new bootstrap.Modal(document.getElementById('changePasswordModal'));
    // 添加值班行
    function addDutyRow() {
        const row = {
            date: '',
            name: '',
            phone: ''
        };
        dutyRows.push(row);
        renderDutyRows();
        updatePreview();
    }

    // 渲染值班行
    function renderDutyRows() {
        const container = document.getElementById('dutyList');
        container.innerHTML = dutyRows.map((row, index) => `
                <div class="duty-row">
                    <div class="row g-3">
                        <div class="col-md-4">
                            <input type="date" class="form-control" 
                                   onchange="updateDutyRow(${index}, 'date', this.value)" 
                                   value="${row.date}">
                        </div>
                        <div class="col-md-3">
                            <input type="text" class="form-control" placeholder="姓名"
                                   onchange="updateDutyRow(${index}, 'name', this.value)" 
                                   value="${row.name}">
                        </div>
                        <div class="col-md-4">
                            <input type="tel" class="form-control" placeholder="电话"
                                   onchange="updateDutyRow(${index}, 'phone', this.value)" 
                                   value="${row.phone}">
                        </div>
                        <div class="col-md-1">
                            <button class="btn btn-outline-danger" onclick="removeDutyRow(${index})">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                    </div>
                </div>
            `).join('');
    }

    // 更新值班行数据
    function updateDutyRow(index, field, value) {
        dutyRows[index][field] = value;
        updatePreview();
    }

    // 删除值班行
    function removeDutyRow(index) {
        dutyRows.splice(index, 1);
        renderDutyRows();
        updatePreview();
    }

    // 背景图对应的样式和布局配置
    const bgConfigs = {
        'zhibanbiao.jpg': {
            styles: {
                borderColor: '#dee2e6',
                headerBgColor: '#f8f9fa',
                headerTextColor: '#495057',
                tableTextColor: '#495057',
                tableFontSize: '20',
                footerColor: '#6c757d',
                footerFontSize: '20',
                thankColor: '#6c757d',
                thankFontSize: '20',
                signatureColor: '#495057',
                signatureFontSize: '24',
                signatureDateColor: '#495057',
                signatureDateFontSize: '24'
            },
            layout: {
                tableX: 100,
                tableY: 550,
                tableWidth: 880,
                rowHeight: 60,
                footerY: 520,
                thankY: 650,
                signatureHeight: 1500,
                signatureWeight: 900
            }
        },
        'chunjie.jpg': {
            styles: {
                borderColor: '#D4AF37',
                headerBgColor: '#8B0000',
                headerTextColor: '#FFFFFF',
                tableTextColor: '#8B0000',
                tableFontSize: '20',
                footerColor: '#8B0000',
                footerFontSize: '20',
                thankColor: '#8B0000',
                thankFontSize: '20',
                signatureColor: '#8B0000',
                signatureFontSize: '24',
                signatureDateColor: '#8B0000',
                signatureDateFontSize: '24'
            },
            layout: {
                tableX: 100,
                tableY: 650,
                tableWidth: 880,
                rowHeight: 65,
                footerY: 620,
                thankY: 750,
                signatureHeight: 1600,
                signatureWeight: 900
            }
        },
        'guoqing.jpg': {
            styles: {
                borderColor: '#BF0A30',
                headerBgColor: '#BF0A30',
                headerTextColor: '#FFFFFF',
                tableTextColor: '#BF0A30',
                tableFontSize: '20',
                footerColor: '#BF0A30',
                footerFontSize: '20',
                thankColor: '#BF0A30',
                thankFontSize: '20',
                signatureColor: '#BF0A30',
                signatureFontSize: '24',
                signatureDateColor: '#BF0A30',
                signatureDateFontSize: '24'
            },
            layout: {
                tableX: 100,
                tableY: 600,
                tableWidth: 880,
                rowHeight: 62,
                footerY: 570,
                thankY: 700,
                signatureHeight: 1550,
                signatureWeight: 900
            }
        },
        'wuyi.jpg': {
            styles: {
                borderColor: '#228B22',
                headerBgColor: '#228B22',
                headerTextColor: '#FFFFFF',
                tableTextColor: '#228B22',
                tableFontSize: '20',
                footerColor: '#228B22',
                footerFontSize: '20',
                thankColor: '#228B22',
                thankFontSize: '20',
                signatureColor: '#228B22',
                signatureFontSize: '24',
                signatureDateColor: '#228B22',
                signatureDateFontSize: '24'
            },
            layout: {
                tableX: 100,
                tableY: 580,
                tableWidth: 880,
                rowHeight: 58,
                footerY: 550,
                thankY: 680,
                signatureHeight: 1520,
                signatureWeight: 900
            }
        }
    };

    // 应用背景图对应的样式和布局
    function applyBgConfig(bgImage) {
        const config = bgConfigs[bgImage];
        if (config) {
            // 应用样式
            Object.keys(config.styles).forEach(key => {
                const element = document.getElementById(key);
                if (element) {
                    element.value = config.styles[key];
                }
            });
            
            // 应用布局
            Object.keys(config.layout).forEach(key => {
                const element = document.getElementById(key);
                if (element) {
                    element.value = config.layout[key];
                }
            });
        }
        updatePreview();
    }

    // 监听背景图选择变化
    document.querySelectorAll('input[name="bgImage"]').forEach(radio => {
        radio.addEventListener('change', (e) => {
            if (e.target.checked) {
                applyBgConfig(e.target.value);
            }
        });
    });

    // 更新预览
    function updatePreview() {
        const canvas = document.getElementById('canvas');
        const ctx = canvas.getContext('2d');

        // 设置画布大小
        canvas.width = 1080;
        canvas.height = 1920;

        // 获取选中的背景图
        const selectedBg = document.querySelector('input[name="bgImage"]:checked').value;

        // 加载背景图
        const img = new Image();
        img.onload = function () {
            // 绘制背景图
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

            // 绘制表格
            drawTable(ctx);

            // 绘制数据
            drawData(ctx);

            // 绘制页脚
            drawFooter(ctx);
        };
        img.src = `/images/zhiban/${selectedBg}`;
    }

    // 绘制表格
    function drawTable(ctx) {
        const headerBgColor = document.getElementById('headerBgColor').value;
        const headerTextColor = document.getElementById('headerTextColor').value;
        const borderColor = document.getElementById('borderColor').value;
        
        // 获取当前布局配置
        const tableX = parseInt(document.getElementById('tableX').value);
        const tableY = parseInt(document.getElementById('tableY').value);
        const tableWidth = parseInt(document.getElementById('tableWidth').value);
        const rowHeight = parseInt(document.getElementById('rowHeight').value);
        
        const totalRows = dutyRows.length + 1;
        const tableHeight = rowHeight * totalRows;

        // 绘制表格背景
        ctx.fillStyle = 'rgba(255, 255, 255, 0.95)';
        ctx.fillRect(tableX, tableY, tableWidth, tableHeight);

        // 绘制表头背景
        ctx.fillStyle = headerBgColor;
        ctx.fillRect(tableX, tableY, tableWidth, rowHeight);

        // 绘制表格边框
        ctx.strokeStyle = borderColor;
        ctx.lineWidth = 1;
        ctx.strokeRect(tableX, tableY, tableWidth, tableHeight);

        // 绘制横线
        for(let i = 1; i < totalRows; i++) {
            ctx.beginPath();
            ctx.strokeStyle = borderColor;
            ctx.setLineDash([5, 5]);
            ctx.moveTo(tableX, tableY + i * rowHeight);
            ctx.lineTo(tableX + tableWidth, tableY + i * rowHeight);
            ctx.stroke();
        }
        ctx.setLineDash([]);

        // 绘制竖线
        const cols = [tableX, tableX + 300, tableX + 600, tableX + tableWidth];
        cols.forEach(x => {
            ctx.beginPath();
            ctx.strokeStyle = borderColor;
            ctx.moveTo(x, tableY);
            ctx.lineTo(x, tableY + tableHeight);
            ctx.stroke();
        });

        // 绘制表头文字
        ctx.font = '24px "Microsoft YaHei"';
        ctx.fillStyle = headerTextColor;
        ctx.textAlign = 'center';

        ctx.fillText('日期', tableX + 150, tableY + 38);
        ctx.fillText('姓名', tableX + 450, tableY + 38);
        ctx.fillText('电话', tableX + 740, tableY + 38);
    }

    // 绘制数据
    function drawData(ctx) {
        const tableX = parseInt(document.getElementById('tableX').value);
        const tableY = parseInt(document.getElementById('tableY').value);
        const rowHeight = parseInt(document.getElementById('rowHeight').value);
        const colWidths = [300, 280, 300];

        const tableFontSize = document.getElementById('tableFontSize').value;
        const tableTextColor = document.getElementById('tableTextColor').value;

        ctx.font = `${tableFontSize}px "Microsoft YaHei"`;
        ctx.fillStyle = tableTextColor;
        ctx.textAlign = 'center';

        dutyRows.forEach((row, i) => {
            let x = tableX;
            const y = tableY + (i + 1) * rowHeight + 38;

            if (i % 2 === 1) {
                ctx.fillStyle = 'rgba(248, 249, 250, 0.5)';
                ctx.fillRect(x, y - rowHeight + 5, colWidths.reduce((a, b) => a + b), rowHeight);
            }

            ctx.fillStyle = tableTextColor;
            ctx.fillText(formatDate(row.date), x + colWidths[0]/2, y);
            x += colWidths[0];

            ctx.fillText(row.name, x + colWidths[1]/2, y);
            x += colWidths[1];

            ctx.fillText(row.phone, x + colWidths[2]/2, y);
        });
    }

    // 绘制页脚
    function drawFooter(ctx) {
        const tableX = parseInt(document.getElementById('tableX').value);
        const tableWidth = parseInt(document.getElementById('tableWidth').value);
        const footerY = parseInt(document.getElementById('footerY').value);
        const thankY = parseInt(document.getElementById('thankY').value);
        const rowHeight = parseInt(document.getElementById('rowHeight').value);

        const footerFontSize = document.getElementById('footerFontSize').value;
        const footerColor = document.getElementById('footerColor').value;
        const thankFontSize = document.getElementById('thankFontSize').value;
        const thankColor = document.getElementById('thankColor').value;
        const signatureFontSize = document.getElementById('signatureFontSize').value;
        const signatureColor = document.getElementById('signatureColor').value;
        const signatureDateFontSize = document.getElementById('signatureDateFontSize').value;
        const signatureDateColor = document.getElementById('signatureDateColor').value;
        const signatureHeight = document.getElementById('signatureHeight').value;
        const signatureWeight = document.getElementById('signatureWeight').value;

        // 绘制底部说明文字
        const footerText = document.getElementById('footerText').value;
        ctx.font = `${footerFontSize}px "Microsoft YaHei"`;
        ctx.fillStyle = footerColor;
        ctx.textAlign = 'left';

        // 文字换行处理
        const indent = '    ';
        const words = (indent + footerText).split('');
        let line = '';
        let lines = [];
        const maxWidth = tableWidth - 40;

        for (let i = 0; i < words.length; i++) {
            const testLine = line + words[i];
            const metrics = ctx.measureText(testLine);
            if (metrics.width > maxWidth) {
                lines.push(line);
                line = words[i];
            } else {
                line = testLine;
            }
        }
        lines.push(line);

        // 绘制多行文字
        lines.forEach((line, i) => {
            ctx.fillText(line, tableX + 20, footerY + (dutyRows.length + 1) * rowHeight + i * 30);
        });

        // 绘制感谢内容
        const footerThankText = document.getElementById('footerThankText').value;
        ctx.font = `${thankFontSize}px "Microsoft YaHei"`;
        ctx.fillStyle = thankColor;

        const wordsThank = (indent + footerThankText).split('');
        let lineThank = '';
        let linesThank = [];
        const maxWidthThank = tableWidth - 40;

        for (let i = 0; i < wordsThank.length; i++) {
            const testLine = lineThank + wordsThank[i];
            const metrics = ctx.measureText(testLine);
            if (metrics.width > maxWidthThank) {
                linesThank.push(lineThank);
                lineThank = wordsThank[i];
            } else {
                lineThank = testLine;
            }
        }
        linesThank.push(lineThank);

        // 绘制感谢内容
        linesThank.forEach((line, i) => {
            ctx.fillText(line, tableX + 20, thankY + (dutyRows.length + 1) * rowHeight + i * 30);
        });

        // 绘制签名
        const signatureText = document.getElementById('signatureText').value;
        const signatureDate = formatSignatureDate(document.getElementById('signatureDate').value);

        ctx.font = `${signatureFontSize}px "Microsoft YaHei"`;
        ctx.fillStyle = signatureColor;
        ctx.textAlign = 'right';

        ctx.fillText(signatureText, signatureWeight, parseInt(signatureHeight));

        ctx.font = `${signatureDateFontSize}px "Microsoft YaHei"`;
        ctx.fillStyle = signatureDateColor;
        ctx.fillText(signatureDate, signatureWeight, parseInt(signatureHeight) + 40);
    }

    // 格式化日期
    function formatDate(dateStr) {
        if (!dateStr) return '';
        const date = new Date(dateStr);
        return `${date.getFullYear()}/${(date.getMonth() + 1).toString().padStart(2, '0')}/${date.getDate().toString().padStart(2, '0')}`;
    }

    // 格式化签名日期
    function formatSignatureDate(dateStr) {
        if (!dateStr) return '';
        const date = new Date(dateStr);
        return `${date.getFullYear()}年${(date.getMonth() + 1)}月${date.getDate()}日`;
    }

    // 导出图片
    function generateImage() {
        const link = document.createElement('a');
        link.download = `值班表_${new Date().getTime()}.png`;
        link.href = canvas.toDataURL('image/png');
        link.click();
    }

    // 添加事件监听
    document.querySelectorAll('input, textarea').forEach(element => {
        element.addEventListener('change', updatePreview);
    });

    // 初始化预览
    updatePreview();

    // 添加一个初始行
    addDutyRow();

    let rowCounter = 0;
    const batchAddModal = new bootstrap.Modal(document.getElementById('batchAddModal'));

    // 复制上一行
    function copyLastRow() {
        if (dutyRows.length > 0) {
            const lastRow = dutyRows[dutyRows.length - 1];
            dutyRows.push({
                date: lastRow.date,
                name: lastRow.name,
                phone: lastRow.phone
            });
            renderDutyRows();
            updatePreview();
        }
    }

    // 显示批量添加模态框
    function showBatchAddModal() {
        batchAddModal.show();
    }

    // 批量添加行
    function batchAddRows() {
        const date = document.getElementById('batchDate').value;
        const name = document.getElementById('batchName').value;
        const phone = document.getElementById('batchPhone').value;
        const count = parseInt(document.getElementById('batchCount').value);

        for (let i = 0; i < count; i++) {
            dutyRows.push({
                date: date,
                name: name,
                phone: phone
            });
        }

        renderDutyRows();
        updatePreview();
        batchAddModal.hide();
    }

    // 打开修改密码模态框
    function openChangePasswordModal() {
        if (changePasswordModal) {
            changePasswordModal.show();
        }
    }

    function validatePassword(password) {
        const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
        return regex.test(password);
    }

    function changePassword() {
        const oldPassword = document.getElementById('oldPassword').value;
        const newPassword = document.getElementById('newPassword').value;
        const confirmPassword = document.getElementById('confirmPassword').value;

        // 清空输入框
        function clearInputs() {
            document.getElementById('oldPassword').value = '';
            document.getElementById('newPassword').value = '';
            document.getElementById('confirmPassword').value = '';
        }

        // 验证输入
        if (!oldPassword || !newPassword || !confirmPassword) {
            Swal.fire({
                icon: 'warning',
                title: '请填写完整',
                text: '请填写所有密码字段',
                confirmButtonText: '确定'
            });
            return;
        }

        if (newPassword !== confirmPassword) {
            Swal.fire({
                icon: 'error',
                title: '密码不匹配',
                text: '新密码与确认密码不一致',
                confirmButtonText: '确定'
            });
            clearInputs();
            return;
        }

        // 验证密码强度
        if (!validatePassword(newPassword)) {
            Swal.fire({
                icon: 'error',
                title: '密码强度不足',
                text: '密码必须包含大小写字母和数字，且长度至少为8位',
                confirmButtonText: '确定'
            });
            clearInputs();
            return;
        }

        // 显示加载中
        Swal.fire({
            title: '处理中...',
            allowOutsideClick: false,
            allowEscapeKey: false,
            showConfirmButton: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        // 发送修改密码请求
        fetch('/api/user/change-password', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                oldPassword: oldPassword,
                newPassword: newPassword
            })
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 关闭修改密码模态框
                    if (changePasswordModal) {
                        changePasswordModal.hide();
                    }

                    // 清空输入
                    clearInputs();

                    // 显示成功消息并跳转
                    Swal.fire({
                        icon: 'success',
                        title: '修改成功',
                        text: '密码已成功修改，请重新登录',
                        allowOutsideClick: false,
                        allowEscapeKey: false,
                        confirmButtonText: '确定'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            window.location.href = '/logout';
                        }
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: '修改失败',
                        text: data.message || '原密码错误或系统异常，请重试',
                        confirmButtonText: '确定'
                    });
                    clearInputs();
                }
            })
            .catch(error => {
                console.error('Error:', error);
                Swal.fire({
                    icon: 'error',
                    title: '系统错误',
                    text: '发生未知错误，请重试',
                    confirmButtonText: '确定'
                });
                clearInputs();
            });
    }
</script>
</body>
</html> 